<template>
  <div class="app-container">
    <div class="flex-box">
      <div class="item">
        <el-button icon="el-icon-circle-plus-outline" @click="addShow">添加商品</el-button>
      </div>
      <div class="item">
        <el-date-picker
          v-model="searchdate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="—"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="getList"
        />
      </div>
      <div class="item">
        <el-input v-model="searchcontent" placeholder="请输入商品名称">
          <el-button slot="append" icon="el-icon-search" @click="getList">搜索</el-button>
        </el-input>
      </div>
      <div class="item">
        <span>总共有{{ total }}条数据</span>
      </div>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%" class="no-r-b"
      :header-cell-style="{background:'#FAFAFA',color:'#666666'}">
      <el-table-column align="center" label="商品主图" width="150">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.spreadid }}</span> -->
          <el-image :src="domainName+(scope.row.image)" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="商品名称">
        <template slot-scope="scope">
          <span>{{ scope.row.proname_zn +'('+ scope.row.proname +')' }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="商品中文名" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.proname_zn }}</span>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="商品类别">
        <template slot-scope="scope">
          <span>{{ scope.row.catenames }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="商品价格">
        <template slot-scope="scope">
          <span>{{ scope.row.price/100 }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="兑换所需积分">
        <template slot-scope="scope">
          <span>{{ scope.row.coin }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="已兑换数量">
        <template slot-scope="scope">
          <span>{{ scope.row.salenum }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="商品详情" width="150">
        <template slot-scope="scope">
          <el-image :src="domainName+(scope.row.content)" />
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.deleted_at | statusFilter">
            {{ row.deleted_at?'已禁用':'正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <div class="caozuo">
            <span type="primary" size="small" icon="el-icon-edit" @click="setImgShow(scope.row)">设置图片</span>
            <span type="primary" size="small" icon="el-icon-edit" @click="editShow(scope.row)">编辑</span>
            <span v-if="scope.row.deleted_at" type="success" size="small" icon="el-icon-thumb" @click="forbiden(scope.row,1)">上架</span>
            <span v-else type="danger" size="small" icon="el-icon-delete" @click="forbiden(scope.row,0)">下架</span>
          </div>
          <!-- <el-button type="primary" size="small" icon="el-icon-edit" @click="discountShow(scope.row)">设置折扣</el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" @click="setImgShow(scope.row)">设置图片</el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" @click="editShow(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.deleted_at" type="success" size="small" icon="el-icon-thumb" @click="forbiden(scope.row,1)">上架</el-button>
          <el-button v-else type="danger" size="small" icon="el-icon-delete" @click="forbiden(scope.row,0)">下架</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-if="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!--列表数据添加/编辑开始  -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" center width="95%" class="user">
      <el-form ref="ruleForm" :model="formRow" label-width="100px">
        <el-form-item label="商品主图">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="doUploadImg"
            :show-file-list="false"
          >
            <img v-if="formRow.image" style="width: 128px;" :src="domainName+(formRow.image)" class="avatar">
            <!-- <span v-else>选择商品主图</span> -->
            <img v-else src="../../../public/img/prod_img.png" />
          </el-upload>
        </el-form-item>
        <el-form-item label="商品英文名">
          <el-input v-model="formRow.proname" auto-complete="off" />
        </el-form-item>
        <el-form-item label="商品中文名">
          <el-input v-model="formRow.proname_zn" auto-complete="off" />
        </el-form-item>
        <!-- <el-form-item label="商品类别">
          <el-select v-model="cids" multiple placeholder="请选择">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename_zn + '(' + item.catename + ')'"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="商品价格">
          <el-input type="number" v-model="price" auto-complete="off" />
        </el-form-item>
        <el-form-item label="兑换所需积分">
          <el-input type="number" v-model="formRow.coin" auto-complete="off" />
        </el-form-item>
        <el-form-item label="已兑换数量">
          <el-input v-model="formRow.salenum" auto-complete="off" />
        </el-form-item>
        <el-form-item label="商品详情">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="doUploadImg1"
            :show-file-list="false"
          >
            <img v-if="formRow.content" style="width: 128px;" :src="domainName+(formRow.content)" class="avatar">
            <!-- <span v-else>选择商品详情图片</span> -->
            <img v-else src="../../../public/img/prod_img.png" />
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--列表数据添加/编辑结束  -->

    <!-- 商品折扣设置开始 -->
    <!-- <el-dialog title="折扣设置" :visible.sync="dialogDiscountVisible">
      <el-form label-position="left" :inline="true">
        <el-form-item v-for="(item,index) in memberLevels" :key="index" :label="item.levelname_zn">
          <el-input v-model="item.discount" placeholder="请输入折扣" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitSet">保存</el-button>
        </el-form-item>
      </el-form>
      <p>
        Tips:数值为100的时候表示没有折扣，90为9折、80为8折，以此类推。
      </p>
    </el-dialog> -->
    <!-- 商品折扣设置结束 -->

    <!-- 商品图片设置开始 -->
    <el-dialog title="图片设置" style="text-align: center;" :visible.sync="dialogImgVisible" @close="closeImgVis">
      <el-upload
        ref="upload"
        action="#"
        list-type="picture-card"
        multiple
        :file-list="showImgData"
        :auto-upload="false"
        :http-request="doUploadImgs"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <i class="el-icon-plus" />
      </el-upload>

      <el-dialog :modal="false" :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
      <br>
      <el-button @click="submitImg">上传图片</el-button>
      <el-button @click="saveProdImg">保存</el-button>
    </el-dialog>
    <!-- 商品图片设置结束 -->
  </div>
</template>

<script>
import { getJPro, addJPro, editJPro, setJProStatus, setJProImg } from '@/api/prod'
import { uploadImg, uploadImgs, getImgs } from '@/api/uploadImg'
import { getLevList } from '@/api/member'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { Message } from 'element-ui'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import imgzip from 'imgzip'

export default {
  name: 'PordList',
  components: { Pagination, UploadExcelComponent },
  filters: {
    statusFilter(status) {
      if (status) {
        status = 'deleted'
      } else {
        status = 'published'
      }
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      cateList: [],
      modules: [], // 弹窗下拉框数据
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      memberLevels: [], // 权限类型
      searchlevel: 0, // 搜索等级
      searchcontent: '', // 搜索内容
      searchdate: '', // 搜索日期
      // 日期插件参数
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 弹窗标题
      dialogTitle: '',
      dialogFormVisible: false,
      dialogUploadVisible: false,
      dialogDiscountVisible: false,
      dialogImgVisible: false,
      // 表单数据
      cids: [],
      formRow: {
        image: '',
        proname: '',
        proname_zn: '',
        price: '',
        coin: '',
        salenum: '',
        content: ''
      },
      setProdId: '',
      // 多图片上传
      showImgData: [],
      uploadImgData: [],
      dialogVisible: false,
      dialogImageUrl: '',
      // 域名
      domainName: process.env.VUE_APP_BASE_DOMAIN
    }
  },
  computed: {
    birthday: {
      get() {
        return new Date(Date.parse(this.formRow.birthday.replace(/-/g, '/')))
      },
      set(val) {
        this.formRow.birthday = val
      }
    },
    price: {
      get() {
        return this.formRow.price / 100
      },
      set(val) {
        console.log(val)
        this.formRow.price = val * 100
      }
    },
    // price: {
    //   get() {
    //     return this.formRow.rprice / 100
    //   },
    //   set(val) {
    //     this.formRow.rprice = val * 100
    //   }
    // },
  },
  watch:{
    // cids() {
    //   console.log(this.cids.join(','))
    //   this.formRow.cids = this.cids.join(',')
    // }
  },
  created() {
    this.getList()
    // this.getCateList()
  },
  methods: {
    // 获取列表数据
    getList() {
      this.listLoading = true
      const search = { searchcontent: this.searchcontent, searchlevel: this.searchlevel }
      if (this.searchdate) {
        const startDate = this.searchdate[0]
        const endDate = this.searchdate[1]
        search.startDate = startDate
        search.endDate = endDate
      }
      const postdata = { ...this.listQuery, ...search }
      getJPro(postdata).then((response) => {
        const { data } = response
        console.log(response, 'getJPro')
        this.list = data.list
        this.total = data.total
        this.listLoading = false
      })
    },
    // 获取商品分类信息
    // getCateList() {
    //   getCates({page: 1,limit: 1000}).then(res=>{
    //     this.cateList = res.data.list
    //   })
    // },
    // 图片上传
    doUploadImg(params) {
      const compress = new imgzip({ quality: 0.5 })
      const _this = this
      // 调用图片压缩
      compress.photoCompress(params.file, function(base64) {
        const blob = imgzip.convertBase64UrlToBlob(base64)
        const formData = new FormData()
        formData.append('images', blob, 'file_' + Date.parse(new Date()) + '.jpg') // 文件对象
        // 上传操作....
        uploadImg(formData).then(response => {
          _this.formRow.image = response.data
        })
      })
    },
    doUploadImg1(params) {
      const compress = new imgzip({ quality: 0.5 })
      const _this = this
      // 调用图片压缩
      compress.photoCompress(params.file, function(base64) {
        const blob = imgzip.convertBase64UrlToBlob(base64)
        const formData = new FormData()
        formData.append('images', blob, 'file_' + Date.parse(new Date()) + '.jpg') // 文件对象
        // 上传操作....
        uploadImg(formData).then(response => {
          _this.formRow.content = response.data
        })
      })
    },
    // 表单提交方法
    submitForm(formName) {
      if (this.formRow.id) {
        // console.log(this.formRow, 'userEdit')
        editJPro(this.formRow).then(res => { // 编辑商品
          Message({
            message: '保存成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.getList()
          this.dialogFormVisible = false
        })
      } else {
        addJPro(this.formRow).then(res => { // 添加商品
          Message({
            message: '保存成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.getList()
          this.dialogFormVisible = false
        })
      }
    },

    // 添加
    addShow() {
      this.cids = []
      this.formRow = {
        image: '',
        proname: '',
        proname_zn: '',
        price: '',
        coin: '',
        salenum: '',
        content: ''
      }
      this.dialogTitle = '商品添加'
      this.dialogFormVisible = true
    },

    // 编辑
    editShow(row) {
      this.formRow = {
        id: row.id,
        image: row.image,
        proname: row.proname,
        proname_zn: row.proname_zn,
        price: row.price,
        coin: row.coin,
        salenum: row.salenum,
        content: row.content
      }
      this.dialogTitle = '商品编辑'
      this.dialogFormVisible = true
    },

    // 上架or下架
    forbiden(row, status) {
      const word = status ? '上架' : '下架'
      this.$confirm('确认' + word + row.proname + '吗?', word + '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setJProStatus({ id: row.id, status: status }).then(res => {
          this.$message({
            type: 'success',
            message: status ? '上架成功' : '下架成功'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: status ? '已取消上架' : '已取消下架'
        })
      })
    },

    // 获取用户等级 折扣设置
    // discountShow(row) {
    //   this.setProdId = row.id
    //   getLevList({ page: 1, limit: 100 }).then(response => {
    //     const { data } = response
    //     for (let index = 0; index < data.list.length; index++) {
    //       data.list[index].discount = ''
    //     }
    //     getProsets({ id: row.id }).then(res => {
    //       console.log(res.data.length == 0)
    //       if (res.data.length != 0) {
    //         for (let index = 0; index < data.list.length; index++) {
    //           for (var key in res.data) {
    //             if (key == data.list[index].id) {
    //               data.list[index].discount = res.data[key]
    //             }
    //           }
    //         }
    //       }
    //       this.memberLevels = data.list
    //       console.log('discountShow', this.memberLevels)
    //     })
    //     this.dialogDiscountVisible = true
    //   })
    // },
    // submitSet() {
    //   console.log('submitSet', this.memberLevels)
    //   let setData = {}
    //   for (let index = 0; index < this.memberLevels.length; index++) {
    //     setData[this.memberLevels[index].id] = Number(this.memberLevels[index].discount)
    //   }
    //   setData = JSON.stringify(setData)
    //   setProd({ proid: this.setProdId, discounts: setData }).then(res => {
    //     console.log(res)
    //     if (res.code == 0) {
    //       this.$message({
    //         type: 'success',
    //         message: '设置成功'
    //       })
    //       this.dialogDiscountVisible = false
    //     }
    //   })
    // },

    // 商品图片设置
    async setImgShow(row) {
      this.setProdId = row.id
      await getImgs({ limit: 100, page: 1, rid: row.id, searchtype: 2 }).then(res => {
        const imgList = []
        const uploadImgList = []
        res.data.list.forEach(item => {
          imgList.push({
            name: '',
            url: this.domainName +  item.src
          })
          uploadImgList.push({
            name: '',
            url: item.src
          })
        })
        this.showImgData = imgList
        this.uploadImgData = uploadImgList
      })
      this.dialogImgVisible = true
    },
    doUploadImgs(params) {
      console.log(params)
      const compress = new imgzip({ quality: 0.5 })
      const _this = this
      // 调用图片压缩
      compress.photoCompress(params.file, function(base64) {
        const blob = imgzip.convertBase64UrlToBlob(base64)
        const formData = new FormData()
        formData.append('images', blob, 'file_' + Date.parse(new Date()) + '.jpg') // 文件对象
        // 上传操作....
        uploadImg(formData).then(response => {
          // _this.imgsData.push(response.data);
          _this.showImgData.push({ name: '', url: _this.domainName + response.data })//显示数据格式
          _this.uploadImgData.push({ name: '', url: response.data })//上传数据格式
        })
      })
    },
    handleRemove(file, fileList) {
      const remurl = (file.url).toString()
      const list = this.uploadImgData.filter(item => {
        return !remurl.includes(item.url)
      })
      this.uploadImgData = list
      console.log(file, fileList, this.uploadImgData, remurl)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    submitImg() {
      this.$refs.upload.submit()
    },
    saveProdImg() {
      console.log(this.showImgData)
      const submitData = []
      this.uploadImgData.forEach(item => {
        submitData.push(item.url)
      })
      console.log(submitData, this.setProdId)
      setJProImg({ proid: this.setProdId, images: submitData }).then(res => {
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.$refs.upload.clearFiles()
          this.dialogImgVisible = false
        }
      })
    },
    closeImgVis() {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped lang="scss">
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.avatar-uploader .el-upload {
    width: 100%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background-color: #E9F6FF;
  }
  .avatar-uploader .el-upload:hover{
    background-color: rgba($color: #E9F6FF, $alpha: 0.7);
  }

  .avatar-uploader .el-upload:hover .avatar-uploader-icon{
    color: rgba($color: #656B78, $alpha: 0.7);
  }
  .avatar-uploader-icon {
    // background-image: url(../../../public/images/headPortrait.png);
    font-size: 18px;
    color: #656B78;
    width: 53px;
    height: 53px;
    line-height: 53px;
    text-align: center;
  }
  .avatar {
    width: 100%;
  }
</style>
